# -*- coding: utf-8 -*-
import hashlib
import json

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.order.db import get_pay, add_pay_success
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

_GATEWAY = 'http://pay.duotpay.com/bank/index.aspx'
_QUERY_GATEWAY = 'http://pay.duotpay.com/bank/search.aspx?orderid={}&parter={}&sign={}'

APP_CONF = {
    '2409': {
        'API_KEY': '1561f8038a08429db7cad553ad4bbb7a',
    },
    '2403': {
        'API_KEY': 'f58fa775763d4e69baa6fadf9cf77d52',
    },
    '2415': {
        'API_KEY': '9bb99d5c77f84e05864140762f35f8c9',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def generate_order_sign(parameter, key):
    s = 'parter={}&type={}&value={}&orderid={}&callbackurl={}{}'.format(
        parameter['parter'], parameter['type'], parameter['value'],
        parameter['orderid'], parameter['callbackurl'], key)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    _LOGGER.info(u'duotpay origin string: %s, sign:%s', s, sign)
    return sign


def generate_query_sign(parameter, key):
    s = 'orderid={}&parter={}{}'.format(parameter['orderid'], parameter['parter'], key)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    _LOGGER.info(u'duotpay origin string: %s, sign:%s', s, sign)
    return sign


def verify_notify_sign(params, key):
    sign = params.pop('sign')
    s = 'orderid={}&opstate={}&ovalue={}{}'.format(params['orderid'], params['opstate'], params['ovalue'], key)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    calculated_sign = m.hexdigest()
    if sign != calculated_sign:
        _LOGGER.info("duotpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    key = _get_api_key(app_id)
    service = info.get('service')
    if service == 'alipay':
        pay_type = 1006
    elif service == 'wechat':
        pay_type = 1007
    else:
        pay_type = 1006
    p_dict = {
        'parter': app_id,
        'type': pay_type,
        'value': pay_amount,
        'orderid': str(pay.id),
        'callbackurl': '{}/pay/api/{}/duotpay/{}'.format(
            settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)
    }
    p_dict['sign'] = generate_order_sign(p_dict, key)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_GATEWAY, data=p_dict, headers=headers, timeout=3)
    resp_obj = response.text
    cache_id = redis_cache.save_html(pay.id, resp_obj)
    charge_resp = {
        'charge_info': settings.PAY_CACHE_URL + cache_id,
    }
    return charge_resp


def check_notify_sign(request, app_id):
    key = _get_api_key(app_id)
    data = dict(request.GET.iteritems())
    _LOGGER.info("duotpay notify data: %s", data)
    verify_notify_sign(data, key)
    pay_id = data['orderid']
    if not pay_id:
        _LOGGER.error("fatal error, pay object not exists, data: %s" % data)
        raise ParamError('duotpay event does not contain valid pay ID')

    pay = get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = int(data['opstate'])
    trade_no = data.get('sysorderid')
    total_fee = float(data['ovalue'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)

    if trade_status == 0:
        _LOGGER.info('duotpay check order success, user_id:%s pay_id:%s' % (mch_id, pay_id))
        add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    pay_id = pay_order.id
    key = _get_api_key(app_id)
    p_dict = {
        'parter': app_id,
        'orderid': str(pay_id),
    }
    p_dict['sign'] = generate_query_sign(p_dict, key)
    response = requests.get(_QUERY_GATEWAY.format(p_dict['orderid'], p_dict['parter'], p_dict['sign']))
    _LOGGER.info(u'duotpay create charge: %s', response.text)
    data = json.loads(response.text)
    if response.status_code == 200:
        trade_status = int(data['opstate'])
        total_fee = float(data['ovalue'])
        trade_no = ''
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        if trade_status == 0:
            _LOGGER.info('duotpay query order success, mch_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            res = add_pay_success(pay_order.mch_id, pay_id, total_fee, trade_no, extend)
            if res:
                async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('duotpay data error, status_code: %s', response.status_code)
